<template>
  <div class="member_list">
    <!-- 搜索栏 -->
    <el-card id="search">
      <el-row style="width: 96.3%">
        <el-col :span="24">
          <el-input
            v-model="searchModel.search_key.name"
            placeholder="规格名称"
            clearable
            @change="getSpecList"
            @clear="searchModel.search_key.name = ''"
          />
          <el-input v-model="searchModel.search_key.planting_tree_name" placeholder="归属树种名称" clearable @change="getSpecList" @clear="searchModel.search_key.planting_tree_name = ''" />
          <el-input
            v-model="searchModel.search_key.donate_amount"
            placeholder="认捐金额"
            clearable
            @change="getSpecList"
            @clear="searchModel.search_key.donate_amount = ''"
          />
          <el-input
            v-model="searchModel.search_key.memo"
            placeholder="备注"
            clearable
            @change="getSpecList"
            @clear="searchModel.search_key.memo = ''"
          />
          <el-select
            v-model="searchModel.search_key.status"
            placeholder="状态"
            clearable
            @change="getSpecList"
            @clear="searchModel.search_key.status = null"
          >
            <el-option
              v-for="item in status"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-date-picker
            v-model="searchModel.search_key.created_at"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="创建开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="getSpecList"
          />
          <el-date-picker
            v-model="searchModel.search_key.updated_at"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="更新开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="getSpecList"
          />
          <el-button type="primary" icon="el-icon-search" @click="getSpecList"
            >查询</el-button
          >
          <el-button icon="el-icon-refresh" @click="clearSearchParams"
            >重置</el-button
          >
          <el-button
            type="warning"
            plain
            icon="el-icon-search"
            @click="exportExcel"
            >导出</el-button
          >
        </el-col>
      </el-row>
      <el-button
        style="position: absolute; right: 30px; top: 20px"
        type="primary"
        icon="el-icon-plus"
        circle
        @click="openEditUI(null)"
      />
    </el-card>

    <!-- 结果列表 -->
    <el-card>
      <el-table :data="userList" stripe style="width: 100%">
        <el-table-column label="序号" width="50" align="center">
          <template slot-scope="scope">
            {{
              (searchModel.page - 1) * searchModel.pageSize + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <!-- planting_tree_name -->
        <el-table-column prop="name" label="规格名称" width="140" align="center">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.name"
              placement="top-start"
            >
              <div>{{ scope.row.name }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="planting_tree_name" label="归属树种" width="104" align="center">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.planting_tree_name"
              placement="top-start"
            >
              <div>{{ scope.row.planting_tree_name }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="donate_amount" label="认捐金额" width="106" align="center" />
        <!-- width="146" -->
        <el-table-column prop="memo" label="备注" align="center">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.memo"
              placement="top-start"
            >
              <div>{{ scope.row.memo }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="70" align="center" />
        <el-table-column prop="status" label="状态" width="90" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 1">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="166" align="center">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.created_at"
              placement="top-start"
            >
              <div>{{ scope.row.created_at }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="更新时间" width="166" align="center">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.updated_at"
              placement="top-start"
            >
              <div>{{ scope.row.updated_at }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="110"
          fixed="right"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              circle
              @click="openEditUI(scope.row.id)"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              circle
              @click="deleteUser(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="searchModel.page"
      :page-sizes="[5, 10, 20, 50, 100]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 用户信息编辑对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      @close="clearForm"
    >
      <el-form ref="userFormRef" :model="userForm" :rules="rules">
        <el-form-item
          label="规格名称"
          prop="name"
          :label-width="formLabelWidth"
        >
          <el-input v-model="userForm.name" placeholder="请输入规格名称" />
        </el-form-item>
        <el-form-item
          label="认捐金额"
          prop="donate_amount"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="userForm.donate_amount"
            placeholder="请输入认捐金额, 两位小数"
          />
        </el-form-item>
        <el-form-item
          v-if="!userForm.id"
          label="归属树种"
          prop="planting_tree_id"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="userForm.planting_tree_id"
            filterable
            placeholder="请选择归属树种"
          >
            <el-option
              v-for="item in treeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- @change="changeUserStatus" -->
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="备注" prop="memo" :label-width="formLabelWidth">
          <el-input v-model="userForm.memo" autocomplete="off"></el-input>
        </el-form-item>
        <!-- {{ userForm.free_parking_expire_at }} -->
        <el-form-item label="排序" prop="sort" :label-width="formLabelWidth">
          <el-input v-model="userForm.sort" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 车牌号 -->
    <!-- <el-dialog
      title="历史车牌号"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <div v-for="(item, index) in carList" :key="item.plate_number">
        <div class="carItem">
          <div>
            <span>车牌号{{ index + 1 }}: </span>
            {{ item.plate_number }}
          </div>
          <div>
            <span>添加时间: </span>
            {{ item.created_at }}
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog> -->
  </div>
</template>

<script>
import specApi from "@/api/specList";
import treeApi from "@/api/treeList";
import exportUtil from "@/excel/ExportExcel";

export default {
  data() {
    return {
      dialogVisible: false,
      carList: [],
      treeList: [],
      status: [
        {
          value: 1,
          label: "启用",
        },
        {
          value: 0,
          label: "禁用",
        },
      ],
      formLabelWidth: "130px",
      userForm: {},
      myUserForm: {},
      dialogFormVisible: false,
      title: "",
      total: 0,
      searchModel: {
        page: 1,
        pageSize: 10,
        search_key: {},
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours(0, 0, 0, 0); // 设置时间为0点0分0秒0毫秒
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近两天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              start.setHours(0, 0, 0, 0); // 设置时间为0点0分0秒0毫秒
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
              start.setHours(0, 0, 0, 0); // 设置时间为0点0分0秒0毫秒
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      userList: [],
      rules: {
        name: [
          { required: true, message: "请输入规格名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        donate_amount: [
          { required: true, message: "请输入认捐金额", trigger: "blur" },
          {
            min: 1,
            max: 16,
            message: "长度在 1 到 16 个字符",
            trigger: "blur",
          },
        ],
        planting_tree_id: [
          { required: true, message: "请选择分配的树种", trigger: "blur" },
          // { validator: checkaccount, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    // this.getSpecList();
  },
  mounted() {
    const id = this.$route.query.id;
    if (id && id !== "undefined") {
      this.searchModel.search_key.planting_tree_id = id;
      this.getSpecList();
    } else {
      // this.searchModel.search_key.planting_tree_id = ""
      this.$router.push(`/tree/specList`);
      this.getSpecList();
    }
    this.getTreeList();
  },
  methods: {
    getTreeList() {
      treeApi
        .getTreeList({
          page: this.searchModel.page,
          pageSize: this.searchModel.pageSize,
        })
        .then((response) => {
          //
          this.treeList = response.data.data;
          // this.total = response.data.total;
          // 图片数组
          // this.srcList = response.data.map(item => item.picture_path)
        });
    },
    open(id) {
      // 请求
      specApi.getCarList(id).then((res) => {
        console.log(res.data);
        // const arr = res.data.map((item) => item.plate_number)
        // const html =
        this.carList = res.data;
        this.dialogVisible = true;
      });
    },
    handleClose() {
      this.dialogVisible = false;
    },
    // 导出
    exportExcel() {
      require.ensure([], () => {
        const fieldName = [
          "序号",
          "规格名称",
          "归属树种",
          "认捐金额",
          "备注",
          "状态",
          "创建时间",
          "更新时间",
        ];
        const filterVal = [
          "index",
          "name",
          "planting_tree_name",
          "donate_amount",
          "memo",
          "status",
          "created_at",
          "updated_at",
        ];
        // const data = this.userList.map(v => filterVal.map(j => v[j]));
        const data = this.userList.map((v, i) =>
          filterVal.map((j) => {
            if (j === "index") {
              return i;
            } else if (j === "sex") {
              return v[j] === 0 ? "未知" : v[j] === 1 ? "男" : "女";
            } else if (j === "status") {
              return v[j] === 0 ? "禁用" : "正常";
            } else {
              return v[j];
            }
          })
        );
        const item = this.userList[0];
        console.log(fieldName, data, `${item.name}`);
        exportUtil.export_json_to_excel(
          fieldName,
          data,
          `${item.name} - ${new Date().toLocaleString().replaceAll("/", "-")}`
        );
        // exportUtil.export_json_to_excel(fieldName, data, `${item.name} - ${new Date().toLocaleDateString().replaceAll('/', '-')}`);
      });
    },
    // 修改启用状态
    changeStatus(e) {
      console.log(e, "status");
      // 确认吗
    }, // changeUserStatus
    changeUserStatus(e) {
      this.userForm.status = e
      console.log(e, "status");
      // 确认吗
    },
    deleteUser(spec) {
      this.$confirm(`您确认删除规格 ${spec.name} ?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(11);
          specApi.deleteSpecById(spec.id).then((response) => {
            this.$message({
              type: "success",
              message: "删除成功" || response.msg,
            });
            this.getSpecList();
          });
        })
        .catch(() => {
          console.log(22);
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        });
    },
    saveUser() {
      // 触发表单验证
      this.$refs.userFormRef.validate((valid) => {
        if (valid) {
          // 提交请求给后台
          // 修改状态
          // const item = { ...this.userList.filter((item) => item.id === this.userForm.id)[0] }
          // if (item.status !== this.userForm.status) {
          //   specApi.updateMemberStatus(this.userForm)
          // }
          // 保存
          specApi.saveSpec(this.userForm).then((response) => {
            // 成功提示
            this.$message({
              message: "保存成功",
              type: "success",
            });
            // 关闭对话框
            this.dialogFormVisible = false;
            // 刷新表格
            this.getSpecList();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    clearForm() {
      this.userForm = {};
      this.$refs.userFormRef.clearValidate();
    },
    openEditUI(id) {
      if (id == null) {
        this.title = "新增种植规格";
      } else {
        this.title = "修改种植规格";
        // 根据id查询用户数据
        // specApi.getUserById(id).then((response) => {
        //   this.userForm = response.data;
        // });
        // 根据分页筛选
        const item = { ...this.userList.filter((item) => item.id === id)[0] };
        this.userForm = item;
      }
      this.dialogFormVisible = true;
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.getSpecList();
    },
    handleCurrentChange(page) {
      this.searchModel.page = page;
      this.getSpecList();
    },
    getSpecList() {
      specApi.getSpecList(this.searchModel).then((response) => {
        //
        this.userList = response.data.data;
        this.total = response.data.total;
      });
    },
    // 重置
    clearSearchParams() {
      this.searchModel = {
        page: 1,
        pageSize: 10,
        search_key: {},
      };
      this.getSpecList();
    },
  },
};
</script>

<style lang="scss" scoped>
.carItem {
  margin-bottom: 12px;
  div {
    margin-bottom: 4px;
    span {
      width: 70px;
      display: inline-block;
    }
  }
}
.member_list {
  .el-table__row .el-table__cell,
  .el-tooltip,
  .el-button .cell {
    white-space: nowrap;
    /* width: 50px; */
    overflow: hidden;
    text-overflow: ellipsis; /* 显示省略号 */
  }
}

/* #search {
  display: flex;
  flex-wrap: wrap;
  .el-input {
    width: 200px;
    margin-right: 15px;
    margin-bottom: 10px;
  }
  .el-date-editor {
    margin-bottom: 12px;
  }
}
 */

.el-select {
  margin-right: 10px;
}
#search {
  display: flex;
  flex-wrap: wrap;
  .el-input {
    width: 190px;
    margin-right: 10px;
    margin-bottom: 10px;
  }
  .el-date-editor {
    margin-right: 12px;
    margin-bottom: 10px;
  }
}
.el-dialog .el-input {
  width: 75%;
}
</style>
